<style scoped>
.system-download-item {
  padding-bottom: 60px;
}
.system-download-item .header {
  min-height: 36px;
}
.system-download-item .header .border {
  width: 100%;
  height: 1px;
  border-bottom: 2px solid #e5e5e5;
  margin-top: 12px;
  margin-bottom: 24px;
}
.footfixed {
  position: fixed;
  z-index: 1000;
  bottom: 0;
  left: 220px;
  right: 0;
  background: #fff;
  padding: 15px 20px;
  border-top: 1px solid #eee;
  margin-bottom: 0 !important;
  text-align: right;
}
</style>
<!--  -->
<template>
  <div class="system-download-item" v-loading="globalLoading">
    <!-- <div class="header">
      <el-row type="flex" justify="end">
        <el-button type="warning" size="small" v-if="system && system.systemType && system.systemType.id === 3"
          @click="categoryTreeShow">分类级别树形结构</el-button>
        <el-button type="primary" @click="onSubmit" size="small">保存</el-button>
        <el-button type="success" @click="onSubmitAndGoSystemList" size="small">保存并返回系统列表</el-button>
        <el-button size="small" @click="goSystemList">返回系统列表</el-button>
      </el-row>
      <div class="border"></div>
    </div> -->
    <el-form ref="downloadForm" :model="download" label-width="130px" v-loading="formLoading">
      <SystemDownloadItemForm ref="systemDownloadItemForm" :download="download" :changeDownload="changeDownload"
        :categories="categories" :globalLoading="globalLoading"/>
      <el-form-item class="footfixed">
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button type="success" @click="onSubmitAndGoSystemList">保存并返回系统列表</el-button>
        <el-button @click="goSystemList">返回系统列表</el-button>
      </el-form-item>
    </el-form>
    <!-- 分类级别树形结构显示 -->
    <TreeDialog :data="categoryTreeDialog" ref="categoryTreeDialog" title="分类级别树形结构显示" />
  </div>
</template>

<script>
import SystemDownloadItemForm from '@/components/main/user/system/download/item/SystemDownloadItemForm.vue'
import TreeDialog from '@/components/common/dialog/TreeDialog.vue'
import * as functions from '@/core/functions.js'
export default {
  created () {
    let query = this.$route.query
    if (!query || !query.sid || !query.id) {
      this.$message.error('未能获取到正确的数据')
      return
    }
    let systemId = query.sid
    let id = query.id
    // 获取系统信息
    this.$post('/system/info', { id: systemId }).then((resoponse) => {
      if (resoponse && resoponse.id) {
        this.system = resoponse

        // 获取所有的分类信息
        this.$post('/category/table-data-infos-by-system-id', { systemId: systemId }).then((resoponse) => {
          if (resoponse.categories) {
            this.categories = resoponse.categories
          } else {
            this.categories = {}
          }
          if (resoponse.categoryIds && resoponse.categoryIds.length > 0) {
            this.download.categoryId = resoponse.categoryIds[0]
          }
          this.initComplete.categories = true
        })

        // 获取内容信息
        if (id > 0) {
          // 修改
          this.$post('/system/download/infofull', { downloadId: id, systemId: systemId }).then(response => {
            if (response && response.sdownload && response.sdownload.id) {
              this.download = initDownload(response)
            } else {
              console.error(response)
            }
            this.initComplete.data = true
            this.initComplete.attr = true
          })
        } else {
          // 新增
          this.initComplete.data = true
          // 获取下载系统属性
          this.$post('/system/download/attr-infos', { systemId: systemId }).then(response => {
            let attr = initAttrByDownloadAttr(response)
            this.download.attr = attr
            this.initComplete.attr = true
          })
        }
      }
      this.initComplete.system = true
    })
  },
  data () {
    return {
      // 全局加载
      globalLoading: true,
      // 表单加载
      formLoading: false,
      // 判断是否加载完成的四个加载项目
      initComplete: {
        categories: false,
        system: false,
        data: false,
        attr: false
      },
      // 获取系统的分类信息
      categories: {},
      // 当前的系统
      system: {},
      // 表单数据
      download: {
        // 基础信息
        base: {
          id: 0,
          systemId: 0,
          isShow: true,
          isTop: false,
          orderNum: 1,
          releasedAt: new Date()
        },
        // 属性信息
        attr: [],
        // 分类信息
        categoryId: -1,
        // 下载的内容信息
        /**
         * {
          id: 0,
          originalFilename:'',
          suffix: ''
        }
         */
        file: {},
        // 下载的显示图标
        fileIcon: {
          id: 0,
          src: '',
          title: '',
          alt: ''
        }
      }
    }
  },
  computed: {
    categoryTreeDialog () {
      let result = getCategoryTreeData(this.categories, 0)
      return result
    },
    downloadName () {
      if (!this.download.attr) {
        return '下载名称'
      }
      let item = this.download.attr.find(element => {
        return parseInt(element.type) === 3
      })
      if (!item) {
        return '下载名称'
      }
      return item.title
    }
  },
  watch: {
    initComplete: {
      handler (newVal) {
        this.$nextTick(() => {
          if (newVal.categories && newVal.system && newVal.data && newVal.attr) {
            // 初始化请求完毕
            this.globalLoading = false
          }
        })
      },
      deep: true
    }
  },
  methods: {
    // 显示分类树形结构
    categoryTreeShow () {
      this.$refs['categoryTreeDialog'].show()
    },
    // 保存
    onSubmit (callback) {
      // 清楚错误信息
      this.$refs['systemDownloadItemForm'].showErrorMessage('')
      // 验证名称是否存在
      let validBool = false
      this.download.attr.forEach(element => {
        if (parseInt(element.type) === 3) {
          let content = element.content.replace(/^(\s|\u00A0)+/, '').replace(/(\s|\u00A0)+$/, '')
          let errorMessage
          if (content.length === 0) {
            errorMessage = '请输入' + this.downloadName
            this.$refs['systemDownloadItemForm'].showErrorMessage(errorMessage)
          } else if (content.length > 200) {
            errorMessage = '输入' + this.downloadName + '不能超过200个字符'
            this.$refs['systemDownloadItemForm'].showErrorMessage(errorMessage)
          } else {
            validBool = true
          }
        }
      })
      if (!validBool) {
        return
      }
      // if (this.download.base.attrStyle === 0 && (!this.download.file || !this.download.file.id)) {
      //   this.$message.error('请选择资源文件')
      //   return
      // }
      // if (this.download.base.attrStyle === 1) {
      //   if (!this.download.base.externallink || this.download.base.externallink.trim() === '') {
      //     this.$message.error('请输入下载外链地址')
      //     return
      //   }
      //   let bool = /^(\/|\/\/|http:\/\/|https:\/\/).*?/.test(this.download.base.externallink.trim())
      //   if (!bool) {
      //     this.$message.error('请输入正确下载外链地址')
      //     return
      //   }
      // }
      if (!this.download.file || !this.download.file.id) {
        this.$message.error('请选择资源文件')
        return
      }
      let param = JSON.parse(JSON.stringify(this.download))
      param.base.isShow = param.base.isShow ? 1 : 0
      param.base.isTop = param.base.isTop ? 1 : 0
      param.base.systemId = this.system.id
      this.formLoading = true
      this.$jpost('/system/download/save-info', param).then(response => {
        if (response && response.sdownload && response.sdownload.id) {
          if (typeof callback === 'function') {
            callback()
          }
          this.download = initDownload(response)
        } else {
          console.error(response)
        }
        this.formLoading = false
      })
    },
    // 保存并返回系统列表
    onSubmitAndGoSystemList () {
      this.onSubmit(() => {
        this.goSystemList()
      })
    },
    // 返回系统列表
    goSystemList () {
      let fullPath = functions.getSystemListPathByItem(this.system)
      if (!fullPath) {
        return
      }

      // 存储系统页面页码，如果从编辑页返回列表页fromItem改为true
      let systbPageCur = JSON.parse(sessionStorage.getItem('systbPageCur' + this.system.id))
      if (systbPageCur) {
        systbPageCur.fromItem = true
        sessionStorage.setItem('systbPageCur' + this.system.id, JSON.stringify(systbPageCur))
      }

      this.$store.dispatch('navAppendAndClose', { path: fullPath, close: this.$route.fullPath })
    },
    // 改变download数据
    changeDownload (download) {
      this.download = download
    }
  },
  components: {
    TreeDialog,
    SystemDownloadItemForm
  }
}

// 初始化 download 数据使其符合 this.download 中的数据格式
function initDownload (data) {
  let base = {
    id: data.sdownload.id,
    systemId: data.sdownload.systemId,
    isShow: data.sdownload.isShow > 0,
    isTop: data.sdownload.isTop > 0,
    orderNum: data.sdownload.orderNum,
    releasedAt: data.sdownload.releasedAt
  }

  let attr = data.listDownloadAttrAndContent.map(element => {
    return {
      id: element.sdownloadAttr.id,
      title: element.sdownloadAttr.title,
      type: element.sdownloadAttr.type,
      proportion: element.sdownloadAttr.proportion,
      isShow: element.sdownloadAttr.isShow > 0,
      isSearch: element.sdownloadAttr.isSearch > 0,
      orderNum: element.sdownloadAttr.orderNum,
      contenId: element.sdownloadAttrContent && element.sdownloadAttrContent.id ? element.sdownloadAttrContent.id : 0,
      content: element.sdownloadAttrContent && element.sdownloadAttrContent.content ? element.sdownloadAttrContent.content : ''
    }
  })

  let categoryId = data.categoryQuote ? data.categoryQuote.scategories.id : -1

  let file = data.fileRepertoryQuote ? {
    id: data.fileRepertoryQuote.hrepertory.id,
    originalFilename: data.fileRepertoryQuote.hrepertory.originalFilename,
    suffix: data.fileRepertoryQuote.hrepertory.suffix
  } : {}

  let fileIcon = {
    id: 0,
    src: '',
    title: '',
    alt: ''
  }
  if (data.fileIconRepertoryQuote) {
    let iconConfig = data.fileIconRepertoryQuote.srepertoryQuote.config
    let jsonConfig = JSON.parse(iconConfig)
    fileIcon = {
      id: data.fileIconRepertoryQuote.hrepertory.id,
      src: functions.getRepertoryImageSrcByHostRepertory(data.fileIconRepertoryQuote.hrepertory),
      title: jsonConfig && jsonConfig.title ? jsonConfig.title : '',
      alt: jsonConfig && jsonConfig.alt ? jsonConfig.alt : ''
    }
  }
  return {
    base, attr, categoryId, file, fileIcon
  }
}

function initAttrByDownloadAttr (data) {
  let result = []
  if (!data || data.length < 1) {
    return []
  }
  data.forEach((element) => {
    result.push({
      id: element.id,
      title: element.title,
      type: element.type,
      proportion: element.proportion,
      isShow: element.isShow > 0,
      isSearch: element.isSearch > 0,
      orderNum: element.orderNum,
      contenId: 0,
      content: ''
    })
  })
  return result
}

// 构建分类树形结构数据
function getCategoryTreeData (data, key) {
  if (data.length < 1) {
    return []
  }
  let result = []
  for (let i in data[key]) {
    let item = data[key][i]
    let children
    if (data.hasOwnProperty(item.id)) {
      children = getCategoryTreeData(data, item.id)
    }
    let element = {}
    element.label = item.name
    if (children) {
      element.children = children
    }
    result.push(element)
  }
  return result
}

</script>
